package com.oocl.euc.core.maintenance.controller;

import com.oocl.euc.core.builder.ApplicationKeyBuilder;
import com.oocl.euc.core.builder.ApplicationKeyValueBuilder;
import com.oocl.euc.core.common.ITTestBase;
import com.oocl.euc.core.maintenance.model.ApplicationKey;
import com.oocl.euc.core.maintenance.model.ApplicationKeyValue;
import com.oocl.euc.core.maintenance.repository.ApplicationKeyRepository;
import com.oocl.euc.core.maintenance.repository.ApplicationKeyValueRepository;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

public class ApplicationKeyControllerIT extends ITTestBase {

    @Autowired
    private ApplicationKeyBuilder applicationKeyBuilder;

    @Autowired
    private ApplicationKeyValueBuilder applicationKeyValueBuilder;

    @Autowired
    private ApplicationKeyRepository applicationKeyRepository;

    @Autowired
    private ApplicationKeyValueRepository applicationKeyValueRepository;

    @After
    public void reset() {
        applicationKeyValueRepository.deleteAll();
        applicationKeyRepository.deleteAll();
    }

    @Test
    public void should_return_application_key_when_given_app_key() throws Exception {
        ApplicationKey applicationKey = applicationKeyBuilder.defaultBuilder()
                .withAppKey("QA_TESTING_RESULT")
                .saveToDB();
        ApplicationKeyValue applicationKeyValue1 = applicationKeyValueBuilder.defaultBuilder()
                .withAppKeyValue("No QA/UAT Testing is needed")
                .withAppKeyId(applicationKey.getId())
                .saveToDB();
        ApplicationKeyValue applicationKeyValue2 = applicationKeyValueBuilder.defaultBuilder()
                .withAppKeyValue("In Progress")
                .withAppKeyId(applicationKey.getId())
                .saveToDB();
        applicationKey.setApplicationKeyValueList(Arrays.asList(applicationKeyValue1, applicationKeyValue2));
        applicationKeyRepository.save(applicationKey);
        mockMvc.perform(get("/rest/appKey/findByAppKey")
                .param("appKey", "QA_TESTING_RESULT"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.appKey").value(applicationKey.getAppKey()))
                .andExpect(jsonPath("$.applicationKeyValueList", Matchers.hasSize(2)))
                .andExpect(jsonPath("$.applicationKeyValueList[0].appKeyValue").value(applicationKeyValue1.getAppKeyValue()))
                .andExpect(jsonPath("$.applicationKeyValueList[1].appKeyValue").value(applicationKeyValue2.getAppKeyValue()));
    }
}